import 'package:flutter/material.dart';
import 'package:flutter_lang/lang_index.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:route_manager/wx_navigator.dart';
import 'package:wallet_home/page/theme/colors.dart';
import 'package:wallet_home/tools/theme_utils.dart';
import '../../image_r.dart';
import '../../module_config.dart';
import '../models/address_item_model.dart';
import './app_bar_controller.dart';
import './simple_search_bar.dart';

class AddressBookPage extends StatefulWidget {
  final String sourcePage;

  AddressBookPage({this.sourcePage = "my"});

  @override
  State<StatefulWidget> createState() => _AddressBookPageState();
}

class _AddressBookPageState extends State<AddressBookPage> {
  // 默认无地址数据
  bool isEmpty = true;
  final AppBarController appBarController = AppBarController();
  List<AddressItem> _items;

  /// 搜索内容元素存储
  bool _isSearch = false;
  List<AddressItem> _filterList = [];
  SlidableController _slidableController;

  @override
  void initState() {
    super.initState();
    _slidableController = SlidableController();
    _items = AddressItem.getAddressList();
    _filterList = AddressItem.getAddressList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          title: Text(
            '${WXLang.$t("home_addressBook_address", package: ModuleConfig.moduleName)}',
            style: TextStyle(
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.grey[200],
                  darkColor: Colors.white),
            ),
          ),
          brightness: Brightness.dark,
          centerTitle: true,
          leading: IconButton(
              icon: Icon(
                Icons.arrow_back,
                color: ThemeUtils.getThemeColor(
                    context: context,
                    brightnessColor: Colors.grey[200],
                    darkColor: Colors.white),
              ),
              onPressed: () {
                WXNavigator.pop(context: context);
              }),
          actions: <Widget>[
            IconButton(
                icon: Icon(Icons.add,
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[300],
                        darkColor: Colors.white)),
                onPressed: () async {
                  AddressItem updateItem = await WXNavigator.pushNamed(
                      context: context, routeName: '/addressNewPage');
                  if (updateItem != null) {
                    print('addressNewPage_back');
                    setState(() {
                      /// 获取修改结果后更新当前列表显示内容
                      _items.add(updateItem);
                      AddressItem.saveAddressList(_items);
                    });
                  }
                })
          ],
        ),
        body: _items.length == 0
            ? emptyWidget
            : Container(
                color: ThemeUtils.getThemeColor(
                    context: context,
                    brightnessColor: Colors.grey[200],
                    darkColor: Colors.black54),
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 40.0,
                      child: _getSearchBarWiget(),
                    ),
                    Expanded(
                      child: Center(
                        child: OrientationBuilder(
                            builder: (context, orientation) =>
                                _getAddressListWidget(context, Axis.vertical)),
                      ),
                    ),
                  ],
                ),
              ));
  }

  Widget _getSearchBarWiget() {
    return SearchAppBar(
      appBarController: appBarController,
      autoSelected: false,
      searchHint:
          '${WXLang.$t("home_inputSearch_address", package: ModuleConfig.moduleName)}',
      mainTextColor: Colors.grey,
      onSearching: (isSearch) {
        _isSearch = isSearch;
        print('onSearching');
        // if (!mounted) {
        print('onSearching -- setState');
        setState(() {});
        // }
        Future.delayed(Duration(milliseconds: 10), () {
          setState(() {});
        });
      },

      /// 默认样式
      mainAppBar: AppBar(
        automaticallyImplyLeading: false,
        titleSpacing: 0.0,
        title: FlatButton(
          onPressed: () {
            setState(() {
              _isSearch = true;
            });
            appBarController.stream.add(true);
          },
          child: Container(
            height: 30.0,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5.0),
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.white,
                  darkColor: Colors.grey[500]),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.search,
                  size: 18.0,
                  color: ThemeUtils.getThemeColor(
                      context: context,
                      brightnessColor: Color(0xFFCCCCCC),
                      darkColor: Colors.white70),
                ),
                SizedBox(
                  width: 2.0,
                ),
                Text(
                  "${WXLang.$t("home_search_address", package: ModuleConfig.moduleName)}",
                  style: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Color(0xFFCCCCCC),
                          darkColor: Colors.white70),
                      fontSize: 16.0),
                ),
              ],
            ),
          ),
        ),
      ),
      onChange: (String search) {
        /// 搜索内容回调
        print('onChange - $search');
        _filterList.clear();
        for (var item in _items) {
          /// 大小写不敏感
          if (item.name.toUpperCase().indexOf(search.toUpperCase()) != -1) {
            _filterList.add(item);
          } else {}
        }
        setState(() {});
      },
      primary: ThemeUtils.getThemeColor(
          context: context,
          brightnessColor: Colors.grey[200],
          darkColor: Colors.grey[800]),
    );
  }

  List<AddressItem> get _getSwitchList {
    if (_isSearch) {
      return _filterList;
    } else {
      return _items;
    }
  }

  Widget _getAddressListWidget(BuildContext context, Axis direction) {
    return ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: _getSwitchList.length,
        itemBuilder: (context, index) {
          return Slidable(
            actionPane: SlidableDrawerActionPane(),
            controller: _slidableController,
            secondaryActions: <Widget>[
              IconSlideAction(
                caption:
                    '${WXLang.$t("home_delete_address", package: ModuleConfig.moduleName)}',
                color: Colors.redAccent,
                icon: Icons.delete,
                onTap: () {
                  print('删除动作 -- ${_isSearch ? '搜索' : '默认'}');
                  setState(() {
                    if (_isSearch) {
                      /// 搜索情况，识别同类元素后删除元素，等待刷新列表
                      AddressItem removeItem = _filterList[index];
                      AddressItem targetItem;
                      for (var item in _items) {
                        if (removeItem.isSameAddress(item)) {
                          targetItem = item;
                          print('删除动作 break---$targetItem');
                          break;
                        }
                      }
                      if (targetItem != null) {
                        _items.remove(targetItem);
                      }
                      print('删除动作后更新数组_filterList break---$index');
                      _filterList.removeAt(index);
                    } else {
                      /// 非搜索情况，只操作数据源
                      _items.removeAt(index);
                    }
                    AddressItem.saveAddressList(_items);
                  });
                },
              )
            ],
            child: AddressItemWidget(
              _getSwitchList[index],
              sourcePage: widget.sourcePage,
              onClick: (updateItem) {
                print('更新成功---${_isSearch ? '搜索' : '默认'}');

                setState(() {
                  if (_isSearch) {
                    /// 搜索情况，识别同类元素后删除元素，等待刷新列表
                    for (var item in _items) {
                      if (updateItem.isSameAddress(item)) {
                        item = updateItem;
                        break;
                      }
                    }
                    _filterList[index] = updateItem;
                  } else {
                    /// 非搜索情况，只操作数据源
                    _items[index] = updateItem;
                  }
                  AddressItem.saveAddressList(_items);
                });
              },
            ),
          );
        });
  }

  get emptyWidget => Center(
        child: Column(
          children: <Widget>[
            Spacer(),
            Image(
              image: AssetImage(ImageR.imagesAddressEmptyIcon,
                  package: ModuleConfig.moduleName),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0),
              child: Text(
                  '${WXLang.$t("home_empty_address", package: ModuleConfig.moduleName)}'),
            ),
            Spacer(),
          ],
        ),
      );
}

class AddressItemWidget extends StatelessWidget {
  final AddressItem item;
  final void Function(AddressItem updateItem) onClick;
  final String sourcePage;

  AddressItemWidget(this.item, {this.onClick, this.sourcePage});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        if (Slidable.of(context)?.renderingMode == SlidableRenderingMode.none) {
          print('跳转到修改地址界面');
          if (sourcePage == "transfer") {
            WXNavigator.pop(result: item.address);
          } else {
            AddressItem updateItem = await WXNavigator.pushNamed(
                context: context,
                routeName: '/addressNewPage',
                arguments: this.item);
            if (onClick != null && updateItem != null) {
              onClick(updateItem);
            }
          }
        } else {
          print('关闭item单元格');
          Slidable.of(context).close();
        }
      },
      child: Column(
        children: [
          Container(
            height: 60.0,
            color: ThemeUtils.getThemeColor(
                context: context,
                brightnessColor: Colors.white,
                darkColor: Colours.dark_bg_color),
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 15.0,
                ),
                Text(
                  item == null ? '' : item.name,
                  style: TextStyle(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Color(0xFF666666),
                        darkColor: Colors.white),
                  ),
                ),
                SizedBox(
                  width: 15.0,
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(right: 15.0),
                    child: Column(
                      textDirection: TextDirection.rtl,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          item == null ? '' : item.coinType,
                          style: TextStyle(
                            color: ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Color(0xFF666666),
                                darkColor: Colors.white),
                          ),
                          overflow: TextOverflow.ellipsis,
                          textDirection: TextDirection.rtl,
                        ),
                        SizedBox(
                          height: 5.0,
                        ),
                        Text(
                          item == null ? '' : item.address,
                          style: TextStyle(
                            color: ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Color(0xFF666666),
                                darkColor: Colors.white),
                          ),
                          overflow: TextOverflow.ellipsis,
                          textDirection: TextDirection.rtl,
                          maxLines: 1,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            color: Colors.grey[350],
          ),
        ],
      ),
    );
  }
}
